<?php
/**
 * key-value存储
 * 对redis封装
 */
class kv
{

	private static $_redis = null; //
	private $config;        //配置信息

	/**
	 * 返回redis实体
	 * @method getInstance
	 * @return [type]      [description]
	 * @author NewFuture
	 */
	public static function getRedis()
	{
		if (self::$_redis == null)
		{
			$config       = Yaf_Registry::get('config')['redis'];
			self::$_redis = new Redis();
			self::$_redis->connect($config['host'], $config['port']);
			//密码验证
			if (isset($config['pwd']))
			{
				self::$_redis->auth($config['pwd']);
			}
			//存放的数据库编号
			if (isset($config['db']))
			{
				self::$_redis->select($config['db']);
			}
		}
		return self::$_redis;
	}

	/**
	 * [写入]
	 * @method set
	 * @param  [type]  $key    [组存KEY]
	 * @param  [type]  $value  [description]
	 * @param  integer $expire [过期时间， 0:表示无过期时间]
	 * @author NewFuture
	 */
	public static function set($key, $value, $expire = 0)
	{
		$value = serialize($value);
		// 永不超时
		if ($expire == 0)
		{
			$ret = self::getRedis()->set($key, $value);
		}
		else
		{
			//如果设置超限时间使用setex($key_name,$timeout,$value)
			$ret = self::getRedis()->setex($key, $expire, $value);
		}
		return $ret;
	}

	/**
	 * 获取键值
	 * @method get
	 * @param  [mixed] $key [支持数组]
	 * @return [type]      [description]
	 * @author NewFuture
	 */
	public static function get($key)
	{
		if (is_array($key))
		{
			$value = self::getRedis()->mGet($key);
			foreach ($value as $k => $v)
			{
				$value['$k'] = @unserialize($v);
			}
		}
		else
		{
			$v = self::getRedis()->get($key);
			$value = @unserialize($v);
		}
		return $value;
	}

	/**
	 * 删除
	 * @method del
	 * @param  [type] $key [description]
	 * @return [type]      [description]
	 * @author NewFuture
	 */
	public static function del($key)
	{
		return self::getRedis()->delete($key);
	}

	/**
	 * [清空数据]
	 * @method clear
	 * @return [boolean] [description]
	 * @author NewFuture
	 */
	public static function clear()
	{
		return self::getRedis()->flushDB();
	}

	// public static function __callStatic($name,$arguments)
	// {

	// }

}